<?php
namespace app\index\controller;
use app\BaseController;
use think\Request;
use \app\index\model;
use think\facade\View;

class Category extends BaseController
{
    //编辑栏目
    public function cp_category_edit(Request $request)
    {
        if($request->isPost()){
            $data = $_POST;//接收
            $user = new model\Category;
            $user->update([
                'name'  => $data['name'],
                'p_id' => $data['p_id'],
                'sort'=>$data['sort']
            ],['id' => $data['id']]);
            if($user){
                $this->success('栏目更新成功');
            }else{
                $this->error('栏目更新失败');
            }
        }

        View::assign([
            //当前栏目信息
            'data'=>model\Category::find($_GET['id']),
            //p_id为0的数据
            'list'=>model\Category::where('p_id',0)->select()
            ]);
        return View::fetch();
    }
    //栏目删除
    public function cp_category_del()
    {
        $arc = model\Article::where('category_id',$_GET['id'])->find();
        if(!empty($arc))$this->error('不能删除,文章中有的栏目');
        $pid = model\Category::where('p_id',$_GET['id'])->find();
        if(!empty($pid))$this->error('该栏目有子栏目,不能删除');
        if(model\Category::find($_GET['id'])->delete()){
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }

    //新增栏目
    public function cp_category_add(Request $request)
    {
        if($request->isAjax()){
            //接收
            $data = $request->post()['data'];
            //验证
            $isPid = [];
            $verify = new \app\index\validate\Category;
            foreach ($data as $v){
                if(!$verify->check($v)){
                    $this->error($verify->getError());
                }
                if($v['p_id'] == 0) $isPid[] = $v['name']; //获取所有新增主栏目名称
            }
            //新增主栏目的名字，是否已存在
            $category = new model\Category;
            $pidName = $category->select()->where('p_id',0)->column('name');
            foreach ($isPid as $v){
                if(in_array($v,$pidName)) $this->error($v.':栏目已存在,请从新输入');
            }
            $category = new model\Category;
            if($category->saveAll($data)){
                $this->success('栏目新增成功');
            }else{
                $this->error('栏目添加失败');
            }
        }

    }

    //栏目管理
    public function cp_category()
    {
        $info =  model\Category::select()->toArray();
        View::assign('list',model\Category::getTree($info));
        return View::fetch();
    }

}